import { thin } from "../thin3.mjs";
import { after } from "./delay_render.mjs";
import { nearest_data } from "./nearest.mjs";
import render_helper from "./render_helper.mjs";
import thin_render from "./thin_render.mjs";

export default function tab_template(container, template) {
  let currenthashpath = document.location.hash;
  let activeindex = template.tab.default || 0;
  let activeitem;

  let i = 0;
  let tab = document.createElement("tab");

  container.appendChild(tab);
  // console.log({ template, type: typeof template.tab });
  if (template.tab instanceof Array) {
    thin_render(tab, template.tab);
    thin("a", tab).each((node) => {
      let reg = RegExp(
        "^".concat(node.getAttribute("href").toLowerCase(), "(?=$|/)"),
        "i"
      );
      // console.log(reg);
      if (reg.test(currenthashpath)) node.classList.add("active");
    });
  } else if (typeof template.tab === "object") {
    activeitem = Object.keys(template.tab.nav)[activeindex];
    for (let item in template.tab.nav) {
      let t = template.tab.nav[item];
      // console.log({ t });
      if (!("when" in t)) {
        render_item();
      }
      if (typeof t.when === "function") {
        if (t.when({ tab, t, data: nearest_data(tab) })) render_item();
      } else if (t.when) {
        render_item();
      }

      function render_item() {
        let t = template.tab.nav[item];
        let nav = document.createElement("tab-nav");
        nav.innerText = t.t || item;
        if (t.hashpath) {
          if (t.click) {
            let temp = t.click;
            t.click = function (e) {
              // if (e)用来判断是实际click，还是主动调用，只有实际click时pushstate
              if (e) history.pushState(null, null, t.hashpath.toLowerCase());
              if (temp) temp(e);
            };
          } else {
            nav.addEventListener("click", (ev) => {
              location.hash = t.hashpath;
            });
          }
          let reg = RegExp("^".concat(t.hashpath.toLowerCase(), "(?=$|/)"));
          if (reg.test(currenthashpath)) {
            activeindex = i;
            activeitem = item;
          }
          i++;
        }

        render_helper(nav, template.tab.nav[item]);
        tab.appendChild(nav);
      }
      // i++;
    }

    // let key = Object.keys(template.tab.nav)[activeindex];
    // console.log({ key });
    tab.childNodes[activeindex].classList.add("active");

    let nav = template.tab.nav[activeitem];
    if (nav.click) after(nav.click); // 将click函数压入afterqueue，当渲染结束时调用。
    thin("tab-nav,a", tab).on("click", (ev) => {
      thin("tab-nav,a", ev.srcElement.parentNode).removeClass("active");
      ev.srcElement.classList.add("active");
    });
  }
}
